<template>
  <view class="video-detail-container">
    <!-- 视频信息 -->
    <view class="video-box">
      <video
        id="myVideo"
        class="video"
        :src="videoList.play_url"
        enable-danmu
        danmu-btn
        controls
        :danmu-list="newDanmuList"
        @error="videoErrorCallback"
      />
      <hot-video-info :data="videoList" />
    </view>

    <!-- 全部评论展示 -->
    <view class="danmu-box">
      <view class="comment-container">
        <view class="all-comment-title">全部评论</view>
        <view class="list">
          <mescroll-body
            ref="mescrollRef"
            @init="mescrollInit"
            :down="{
              use: false
            }"
            @up="upCallback"
            :up="{
              textNoMore: '~ 我也是有底线的 ~'
            }"
          >
            <block v-for="(item, index) in CommentList" :key="index">
              <article-comment-item :data="item"></article-comment-item>
            </block>
          </mescroll-body>
        </view>
      </view>
    </view>

    <!-- 底部功能区 -->
    <article-operate
      :placeholder="'发个弹幕，开心一下'"
      @commitClick="onCommitClick"
      :articleData="videoList"
    ></article-operate>
    <!-- 弹出层 -->
    <uni-popup ref="popup" type="bottom" @change="onCommitPopupChange">
      <article-comment-commit v-if="isShowCommit" :articleId="videoList.id" @success="onSuccess" />
    </uni-popup>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import { _getVideoDanmuList, _getVideoCommentList } from '../../../api/video'
// 2. 导入 mixin
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js'
export default {
  // 3. 注册 mixin
  mixins: [MescrollMixin],
  data() {
    return {
      danmuList: [], // 弹幕数据源
      moreDanmu: true,
      mescroll: null, // mescroll-uni实例对象
      page: 1,
      size: 5,
      CommentList: [], // 视频评论
      init: true, //
      isShowCommit: false,
      videoContext: null,
      newDanmuList: [] // 解决弹幕不显示或只显示一条问题
    }
  },
  computed: {
    ...mapState('video', ['videoList'])
  },
  onReady() {
    this.videoContext = uni.createVideoContext('myVideo') // 获取video实例
  },
  created() {
    this.getVideoDanmuList()
    console.log(this.videoList)
  },
  mounted() {
    this.mescroll = this.$refs.mescrollRef.mescroll
  },
  methods: {
    /**
     * 视频弹幕
     */
    async getVideoDanmuList() {
      const { list } = await _getVideoDanmuList({ videoId: this.videoList.id })
      // 弹幕之所以不显示，是因为我们修改了 `danmuList` 的数据源导致的，这个问题其实为 `video` 组件的 `bug` 。
      this.newDanmuList = [...list] // 解决方案 深拷贝 `danmuList` 到一个新的数组，用于展示 **弹幕列表**
      console.log(this.newDanmuList)
    },
    /**
     * 视频评论
     */
    async getVideoCommentList() {
      const { list } = await _getVideoCommentList({ videoId: this.videoList.id, page: this.page, size: this.size })
      if (this.page === 1) {
        this.CommentList = list
      } else {
        this.CommentList = [...this.CommentList, ...list]
      }
      console.log(this.CommentList)
    },
    /**
     * 首次加载
     */
    mescrollInit() {
      this.getVideoCommentList()
      // 关闭 上拉加载 && 下拉刷新动画
      this.init = false
      this.mescroll.endSuccess()
      // this.mescroll.endBySize(this.CommentList.length, this.newDanmuList.length)
    },
    /**
     * 上拉加载
     */
    async upCallback() {
      if (this.init) return
      console.log('upCallback')
      this.page += 1
      await this.getVideoCommentList()
      this.mescroll.endBySize(this.CommentList.length, this.newDanmuList.length)
      // 关闭 上拉加载 && 下拉刷新动画
      this.mescroll.endSuccess()
      // 判断数据是否加载完成
      // 在 `mescroll` 中提供了对应的对比方法：`mescroll.endBySize(当前数据量，总数据量)`
      console.log(this.newDanmuList.length)
    },
    /**
     * 弹出弹窗
     */
    onCommitClick() {
      this.$refs.popup.open()
    },
    /**
     * 监听popup
     */
    onCommitPopupChange(e) {
      // 解决输入框内容关闭后仍然存在问题
      if (e.show) {
        this.isShowCommit = e.show
      } else {
        // 解决隐藏时动画过快隐藏问题，延时隐藏
        setTimeout(() => {
          this.isShowCommit = e.show
        }, 200)
      }
    },
    /**
     * 发表弹幕成功的回调
     */
    onSuccess(res) {
      // 通过video实例调用sendDanmu方法 发送弹幕
      this.videoContext.sendDanmu({
        text: res.info.content, // 发送的内容
        color: this.getRandomColor() // 弹幕颜色
      })
      // 添加弹幕到数据源
      this.danmuList.unshift(res.info)
      this.CommentList.unshift(res.info)
      // 关闭 popup 弹出层
      this.$refs.popup.close()
      // 提示用户
      uni.showToast({
        title: '发表成功',
        icon: 'success'
      })
      this.mescroll.endBySize(this.CommentList.length, this.newDanmuList.length)
      console.log(res)
    },
    /**
     * 发送弹幕失败回调
     */
    videoErrorCallback(e) {
      uni.showModal({
        content: e.target.errMsg,
        showCancel: false
      })
    },
    /**
     * 弹幕随机颜色
     */
    getRandomColor: function () {
      const rgb = []
      for (let i = 0; i < 3; ++i) {
        let color = Math.floor(Math.random() * 256).toString(16)
        color = color.length == 1 ? '0' + color : color
        rgb.push(color)
      }
      return '#' + rgb.join('')
    }
  }
}
</script>

<style lang="scss" scoped>
.video-detail-container {
  .video-box {
    background-color: $uni-bg-color;
    position: sticky;
    top: 0;
    z-index: 9;
    .video {
      width: 100%;
      height: 230px;
    }
  }
  .danmu-box {
    border-top: $uni-spacing-col-sm solid $uni-bg-color-grey;
    margin-bottom: 36px;
    .list {
      /* #ifdef H5 */
      padding-bottom: 74px;
      /* #endif */
      /* #ifndef H5 */
      padding-bottom: 42px;
      /* #endif */
    }
    .comment-container {
      padding: $uni-spacing-col-lg $uni-spacing-row-lg;
      .all-comment-title {
        font-size: $uni-font-size-lg;
        font-weight: bold;
      }
    }
    .allList {
      color: $uni-color-primary;
      text-align: center;
      padding: 8px 0;
    }
  }
}
</style>
